import { useRouter } from 'vue-router'
import { storeToRefs } from 'pinia'
import { useAccountStore } from '@/store/account'
import { useAdDialogStore } from '@/store/ad-dialog'
import { useAppStore } from '@/store/app'
import { useCreatorStore } from '@/store/creator'
import { useFeedback } from '@/store/feedback.js'
import { usePopupDialogStore } from '@/store/popup-dialog'
import { usePopupMessageStore } from '@/store/popup-message'
import { usePremiumCelebrationStore } from '@/store/premium/animation'
import { $t } from '@/i18n'
import { notifyBlock } from '@/utils/state-broadcast'
import { toFixedString } from '@/utils/string-helper'
import Discount from '@/components/dialogs/remark-slot/premium/Discount.vue'
import Sale from '@/components/dialogs/remark-slot/premium/Sale.vue'
import Season from '@/components/dialogs/remark-slot/premium/Season.vue'
import {
  BLOCK_UPDATE,
  CONSUME_TYPE,
  FAVORITE_TAB,
  POPUP_AD_DIALOG,
  POPUP_DIALOG_TYPE,
  PREMIUM_MEMBER,
  REWARD_TYPE,
} from '@/constant'
import { MEDIA_TYPE } from '@/constant/publish'
import { TAB_NAMES as SEARCH_TAB_NAMES, TAB_TYPE as SEARCH_TAB_TYPE } from '@/constant/search'
import { trackEvent } from '@/gtm'
import API from '@/http'
import { usePaymentDialog } from './payment'

export function useDialog() {
  const { $popupDialog, $selection, $alert, close } = usePopupDialogStore()
  const { open } = usePopupMessageStore()
  const { getCreator } = useCreatorStore()

  const { reset } = useFeedback()

  const accountStore = useAccountStore()
  const { userId, userData, isVip, isLogin } = storeToRefs(accountStore)
  const { afterLoginAction, refetchUserDetail } = accountStore

  const appStore = useAppStore()
  const { appConfig } = storeToRefs(appStore)

  const { $openAdDialog } = useAdDialogStore()

  const router = useRouter()

  async function premium({ premiumType }) {
    if (!premiumType) throw new Error('premiumType is required')

    const memberMonth = appConfig.value.config.member_type_list.find((item) => item.id === PREMIUM_MEMBER.MONTH)
    const memberSeason = appConfig.value.config.member_type_list.find((item) => item.id === PREMIUM_MEMBER.SEASON)
    const amount = premiumType === PREMIUM_MEMBER.MONTH ? memberMonth.price : memberSeason.price

    const successDialogConfig = {
      image: userData.value?.avatar ?? '',
      title: $t('dialog.premiumSuccess.title'),
      showConfirm: true,
      confirmText: $t('dialog.premiumSuccess.confirm'),
      confirm: () => {
        console.log('繼續查看您的會員權益')
      },
    }

    let popupDialogConfig

    if (!isVip.value) {
      popupDialogConfig = {
        image: userData.value?.avatar ?? '',
        title: $t('dialog.premium.title'),
        content: { amount },
        confirm: () => console.log('premium.confirm'),
        confirmText: $t('dialog.premium.confirm', { amount }),
        confirmGradient: true,
      }

      if (premiumType === PREMIUM_MEMBER.SEASON) {
        popupDialogConfig.remarkSlot = {
          component: Season,
          props: { amount: memberSeason.price },
        }
      }
    } else {
      popupDialogConfig = {
        image: userData.value?.avatar ?? '',
        title: $t('dialog.premiumRenew.title'),
        content: { amount, renew: true },
        confirm: () => console.log('premium.confirm'),
        cancel: () => console.log('premium.cancel'),
        confirmText: $t('dialog.premiumRenew.confirm'),
        cancelText: $t('dialog.premiumRenew.cancel'),
        cancelLightTheme: true,
      }
    }

    const { single, multiple } = usePaymentDialog({
      popupDialogType: POPUP_DIALOG_TYPE.PREMIUM,
      popupDialogConfig,
      payActionConfig: {
        api: API.Payment.premium,
        checkApi: API.Payment.checkPremium,
        paymentType: CONSUME_TYPE.PREMIUM,
        amount,
        actions: {
          onSuccess: () => {
            $popupDialog(POPUP_DIALOG_TYPE.PREMIUM_SUCCESS, successDialogConfig).open()
            usePremiumCelebrationStore().open()
            refetchUserDetail()
          },
          onFailure: () => console.log('onFailure'),
          onCancel: () => console.log('onCancel'),
        },
        payloadFactory: () => ({ id: premiumType }),
      },
    })

    isVip.value ? multiple() : single()
  }

  /**
   * 打賞
   * @param {*} toMedia 打賞的對象是不是媒體
   * @returns void
   */
  async function donate(item, gtmKey, toMedia = false) {
    // 不能donate給自己
    if (isSameAff({ aff: item.author?.aff, message: $t('content.chat.canNotDonateToSelf'), fallback: void 0 })) return

    const { uuid } = await getCreator(item.author.aff)

    let tipResult = {}

    const { multiple } = usePaymentDialog({
      popupDialogType: POPUP_DIALOG_TYPE.TIP,
      popupDialogConfig: {
        image: item.author?.avatar,
        title: $t('title.donate', { nickname: item.author?.nickname }),
        subtitle: $t('subtitle.donate'),
        content: { author: item.author },
        confirm: async (data) => (tipResult = data),
        confirmText: $t('common.send'),
      },
      payActionConfig: {
        api: API.Payment.reward,
        checkApi: API.Payment.checkReward,
        paymentType: CONSUME_TYPE.REWARD,
        userUUID: uuid,
        actions: {
          onSuccess: () => {
            router.push({ name: 'message', query: { id: item.author.aff } })
          },
          onFailure: () => console.log('onFailure'),
          onCancel: () => console.log('onCancel'),
        },
        payloadFactory: () => {
          return {
            type: toMedia
              ? item.type === MEDIA_TYPE.VIDEO
                ? REWARD_TYPE.VIDEO
                : REWARD_TYPE.PHOTO
              : REWARD_TYPE.CREATOR,
            info_id: toMedia ? item.id : item.author.aff,
            aff: item.author.aff,
            author_aff: item.author.aff,
            amount: tipResult.amount,
            message: tipResult.message,
          }
        },
      },
    })

    multiple()
    gtmTrack(gtmKey, item)
  }

  function subscribe({
    item = { author: { aff: {}, avatar: {}, nickname: {}, username: {}, price: {} } },
    gtmKey = null,
    showClose = true,
    showCancel = true,
  }) {
    // 不能訂閱自己
    if (
      isSameAff({
        aff: item.author?.aff,
        message: $t('content.subscribe.canNotSubToSelf'),
      })
    )
      return

    const successDialogConfig = {
      image: item.author?.avatar,
      title: $t('title.subscribe.success', { nickname: item.author?.nickname }),
      content: {
        nickname: item.author?.nickname,
      },
      showClose,
      showConfirm: true,
      confirmText: $t('common.goAround'),
      confirm: () => {
        router.push({ name: 'creator', params: { username: item.author?.username } })
      },
    }

    if (showCancel) {
      successDialogConfig.cancel = () => {}
      successDialogConfig.cancelText = $t('common.checkItOut')
    }

    const amount = getSaleAmount({ amount: item.author?.price })
    const originAmount = item.author?.price

    const popupDialogConfig = {
      image: item.author?.avatar,
      title: $t('label.subscribe') + item.author?.nickname,
      content: {
        author: item.author,
        amount,
      },
      confirm: () => {},
      confirmGradient: true,
      confirmText: $t('label.subscribeBtn', { dollarSign: '$', price: amount }),
    }

    decorateDialogConfig({
      config: popupDialogConfig,
      options: { amount, originAmount, paymentType: CONSUME_TYPE.SUBSCRIBE },
    })

    const { multiple } = usePaymentDialog({
      popupDialogType: POPUP_DIALOG_TYPE.SUBSCRIBE,
      popupDialogConfig,
      payActionConfig: {
        api: API.Payment.subscribe,
        checkApi: API.Payment.checkSubscribe,
        paymentType: CONSUME_TYPE.SUBSCRIBE,
        amount,
        actions: {
          onSuccess: () => {
            $popupDialog(POPUP_DIALOG_TYPE.SUBSCRIBE_SUCCESS, successDialogConfig).open()
          },
          onFailure: () => console.error('[subscribe.onFailure] 訂閱失敗'),
          onCancel: () => console.log('[subscribe.onCancel] 訂閱取消'),
        },
        payloadFactory: () => ({ author_aff: item.author.aff }),
      },
    })

    multiple()
    gtmKey && gtmTrack(gtmKey, item)
  }

  function shopBuy(item) {
    // 不能買自己的商品
    if (
      isSameAff({
        aff: item.author?.aff,
        message: $t('content.shopBuy.canNotBuyToSelf'),
      })
    )
      return

    const amount = getSaleAmount({ amount: item?.money })
    const originAmount = item?.money

    const popupDialogConfig = {
      image: item.author?.avatar,
      title: $t('title.buyGoods'),
      content: {
        nickname: item.author?.nickname,
        amount,
      },
      confirm: async () => {},
      confirmGradient: true,
      confirmText: $t('label.shopBuyBtn', { price: amount, dollarSign: '$' }),
    }

    decorateDialogConfig({
      config: popupDialogConfig,
      options: { amount, originAmount, paymentType: CONSUME_TYPE.SHOP_BUY },
    })

    const { multiple } = usePaymentDialog({
      popupDialogType: POPUP_DIALOG_TYPE.SHOP_BUY,
      popupDialogConfig,
      payActionConfig: {
        api: API.Payment.shopBuy,
        checkApi: API.Payment.checkShopBuy,
        paymentType: CONSUME_TYPE.SHOP_BUY,
        amount,
        actions: {
          onSuccess: () => {
            $popupDialog(POPUP_DIALOG_TYPE.SHOP_BUY_SUCCESS, {
              image: item.author?.avatar,
              title: $t('title.shopBuy.success', { nickname: item.author?.nickname }),
              content: {
                nickname: item.author?.nickname,
                show_caption: true,
              },
              showClose: true,
              showConfirm: true,
              confirmText: $t('common.iKnow'),
              confirm: () => {
                const type = item.type === MEDIA_TYPE.VIDEO ? 'video' : 'photo'
                router.push({
                  name: 'share-media',
                  params: { username: item.author?.username, mediaType: type, id: item.id },
                })
              },
            }).open()
          },
        },
        payloadFactory: () => ({ id: item.id, author_aff: item.author?.aff }),
      },
    })

    multiple()
    gtmTrack(26, item)
  }

  function chatBuy({ item, creator }) {
    if (
      isSameAff({
        aff: item.fromAff,
        message: $t('content.shopBuy.canNotBuyToSelf'),
      })
    )
      return

    const amount = getSaleAmount({ amount: item.price })
    const originAmount = item.price

    const popupDialogConfig = {
      image: creator.avatar,
      title: $t('dialog.chatBuy.title'),
      content: {
        amount,
        count: item.media_list.length,
        nickname: creator.nickname,
      },
      confirm: async () => {},
      confirmText: $t('message.goToPayAmount', { amount }),
      confirmGradient: true,
      showCancel: false,
      cancelLightTheme: true,
    }

    decorateDialogConfig({
      config: popupDialogConfig,
      options: { amount, originAmount, paymentType: CONSUME_TYPE.CHAT_BUY },
    })

    const { multiple } = usePaymentDialog({
      popupDialogType: POPUP_DIALOG_TYPE.CHAT_BUY,
      popupDialogConfig,
      payActionConfig: {
        api: API.Payment.chatBuy,
        checkApi: API.Payment.checkChatBuy,
        paymentType: CONSUME_TYPE.CHAT_BUY,
        amount,
        actions: {
          onSuccess: () => {
            $popupDialog(POPUP_DIALOG_TYPE.SHOP_BUY_SUCCESS, {
              image: creator.avatar,
              title: $t('title.shopBuy.success', { nickname: creator.nickname }),
              content: {
                nickname: creator.nickname,
                num: item.media_list.length,
                show_caption: true,
              },
              showConfirm: true,
              confirmText: $t('common.iKnow'),
              confirm: () => {},
            }).open()
          },
        },
        payloadFactory: () => ({ id: item.id, author_aff: item.fromAff }),
      },
      extraData: item,
    })

    multiple()
    gtmTrack(74, item)
  }

  function chatSubscribe({ item }) {
    if (
      isSameAff({
        aff: item.fromAff,
        message: $t('content.shopBuy.canNotBuyToSelf'),
      })
    )
      return

    const amount = getSaleAmount({ amount: item.price })
    const originAmount = item.price

    const popupDialogConfig = {
      image: item.author?.avatar,
      title: $t('label.subscribe') + item.author?.nickname,
      content: {
        author: item.author,
        amount,
      },
      confirm: () => {},
      confirmGradient: true,
      confirmText: $t('dialog.chatSubscribe.btn', { price: amount }),
    }

    decorateDialogConfig({
      config: popupDialogConfig,
      options: { amount, originAmount, paymentType: CONSUME_TYPE.CHAT_SUBSCRIBE },
    })

    const { multiple } = usePaymentDialog({
      popupDialogType: POPUP_DIALOG_TYPE.SUBSCRIBE,
      popupDialogConfig,
      payActionConfig: {
        api: API.Payment.chatBuy,
        checkApi: API.Payment.checkChatBuy,
        paymentType: CONSUME_TYPE.CHAT_SUBSCRIBE,
        amount,
        actions: {
          onSuccess: () => {
            $popupDialog(POPUP_DIALOG_TYPE.SUBSCRIBE_SUCCESS, {
              image: item.author?.avatar,
              title: $t('title.subscribe.success', { nickname: item.author?.nickname }),
              content: {
                nickname: item.author?.nickname,
              },
              showClose: true,
              showConfirm: true,
              confirmText: $t('common.goAround'),
              cancelText: $t('common.checkItOut'),
              confirm: () => {
                router.push({ name: 'creator', params: { username: item.author?.username } })
              },
              cancel: () => {},
            }).open()
          },
        },
        payloadFactory: () => ({ id: item.id, author_aff: item.fromAff }),
      },
      extraData: item,
    })

    multiple()
    gtmTrack(73, item)
  }

  async function more(aff, id) {
    const creator = await getCreator(aff)
    const isBlock = creator.is_block
    const type = isBlock ? BLOCK_UPDATE.CANCEL_BLOCK : BLOCK_UPDATE.ADD_BLOCK
    const blockMsg = {
      title: isBlock ? $t('common.unblock') : $t('common.block'),
      success: isBlock ? $t('common.hasUnblocked') : $t('common.hasBlocked'),
      fail: isBlock ? $t('common.unblockFail') : $t('common.blockFail'),
    }
    const selection = isLogin.value ? [$t('common.report'), blockMsg.title] : [$t('common.report')]

    $selection(selection, {
      confirm: async (selected) => {
        if (selected === 1) {
          // console.log('媽啊他按了封鎖而且封鎖沒有下一個popup dialog跳出我只能在這邊做事情捏')
          try {
            await API.Block.update({
              data: {
                type,
                aff_blocked: aff,
              },
            })

            notifyBlock(aff, !isBlock)

            const { nickname } = await getCreator(aff)
            open(blockMsg.success + nickname)
          } catch (e) {
            open(blockMsg.fail)
            throw e
          }
        }
      },
    })
      .next([
        {
          type: POPUP_DIALOG_TYPE.ACCUSE,
          title: $t('common.report'),
          confirm: async (d) => {
            const data = {
              reported_aff: aff,
              report_reason: d.reason,
              report_content: d.content,
            }
            if (id) {
              data.info_id = id
            }

            try {
              await API.Home.report({ data })
              open($t('common.reportSuccess'))
            } catch (e) {
              open($t('common.reportFail'))
              throw e
            }
          },
          confirmText: $t('common.report'),
          cancel() {},
        },
        // {
        //   type: POPUP_DIALOG_TYPE.CONFIRM,
        //   title: '封鎖他',
        //   content: '你確定再也不想看到他？',
        //   confirm: () => {},
        //   cancel: () => {},
        // },
      ])
      .open()
  }

  function gtmTrack(key, item) {
    const meta = { aff: item?.author?.aff || item?.toAff }
    if (item.id) {
      meta.id = item.id
    }
    meta.aff && trackEvent({ key, meta })
  }

  function feedback() {
    $popupDialog(POPUP_DIALOG_TYPE.MINE_FEEDBACK, {
      title: $t('title.report'),
      // content: ,
      confirm: async (d) => {
        const data = {
          type: d.type,
          content: d.content,
          attachment: d.attachment,
          email: d.email,
        }
        console.log(`feedback data:`, data)
        try {
          await API.Auth.feedback({ data })
          reset()
        } catch (e) {
          console.log(e)
          open(e)
          throw e
        }
      },
      confirmText: $t('common.submitFeedback'),
      cancel() {},
    })

    $alert({
      title: $t('info.feedbackSuccess'),
      content: $t('info.feedbackToCs'),
      confirmText: $t('info.understand'),
      fromCenter: true,
      showClose: false,
    }).open()
  }

  function isSameAff({ aff, message = $t('message.isSameAff'), fallback = () => {} }) {
    if (aff === userId.value) {
      $alert({
        content: message,
        confirm: fallback,
        showClose: false,
      }).open()
      return true
    }
    return false
  }

  /** 計算 Premium 折扣金額
   * @param {Object} options
   * @param {Number} options.amount - 金額
   * @param {Boolean} options.forDecorate - 是否為裝飾用
   */
  function getSaleAmount({ amount, forDecorate = false }) {
    return toFixedString(isVip.value || forDecorate ? amount * appConfig.value.premium_discount : amount, 2)
  }

  /** 裝飾 popupDailog 根據狀態添加相對應的屬性
   * @param {Object} options
   * @param {Object} options.config - popupDialogConfig
   * @param {Object} options.options - 裝飾選項
   * @param {Number} options.options.amount - 金額
   * @param {Number} options.options.originAmount - 原始金額
   * @param {String} options.options.paymentType - 支付類型
   */
  function decorateDialogConfig({ config, options = { amount: null, originAmount: null, paymentType: null } }) {
    if (!isVip.value && options.amount) {
      config.remarkSlot = { component: Sale, callback: openPremiumDialog }
    }

    if (isVip.value && options.originAmount) {
      const amount = toFixedString(options.originAmount, 2)
      config.remarkSlot = {
        component: Discount,
        props: { amount, ...remarkProps(options.paymentType) },
        callback: openPremiumDialog,
      }
    }
  }

  function openPremiumDialog() {
    close()
    $openAdDialog(POPUP_AD_DIALOG.PREMIUM).open()
  }

  function remarkProps(paymentType) {
    const map = {
      [CONSUME_TYPE.SUBSCRIBE]: { showPerMonth: true },
      [CONSUME_TYPE.SHOP_BUY]: { showPerMonth: false },
      [CONSUME_TYPE.CHAT_BUY]: { showPerMonth: false },
      [CONSUME_TYPE.CHAT_SUBSCRIBE]: { showPerMonth: true },
    }
    return map[paymentType] ?? {}
  }

  return {
    premium: afterLoginAction(premium),
    donate: afterLoginAction(donate),
    subscribe: afterLoginAction(subscribe),
    shopBuy: afterLoginAction(shopBuy),
    chatBuy: afterLoginAction(chatBuy),
    chatSubscribe: afterLoginAction(chatSubscribe),
    more,
    feedback,
  }
}
